package com.nic.view.util;

import java.util.Locale;

/**
 * String utils
 * @author Larry
 *
 */
public class StringUtils {




    /**
     * Convert byte[] to hex string.
     * @param
     * @return hex string
     */
    public static String bytesToHexString(byte by){
        byte src [] = new byte[]{by};
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Convert byte[] to hex string.
     * @param src byte[] data
     * @return hex string
     */   
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase(Locale.CHINA);
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    /**
     * 十六进制转换字符串
     * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr)
    {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++)
        {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * short转byte数组(小端模式，低位在前，高位在后)
     * @param s short数字
     * @return 数组
     */
    public static byte[] shortToByteArray(short s) {
        byte[] shortBuf = new byte[2];

        for(int i=0;i<2;i++) {
            int index = shortBuf.length - 1 -i;
            int offset = index*8;
            shortBuf[index] = (byte)((s>>>offset)&0xff);
        }
        return shortBuf;
    }

    /**
     * 注释：字节数组到short的转换
     *
     * @param b 数组
     * @return short值
     */
    public static short byteArrayToShort(byte[] b) throws ArrayIndexOutOfBoundsException {
        short s;
        short s0 = (short) (b[0] & 0xff);// 最低位
        short s1 = (short) (b[1] & 0xff);
        s1 <<= 8;
        s = (short) (s0 | s1);
        return s;
    }


    /**
      * 字节转换为浮点
      *
      * @param b 字节（至少4个字节）
      * @param index 开始位置
      * @return
      */
           public static float byte2float(byte[] b, int index) {
           int l;
           l = b[index];
           l &= 0xff;
           l |= ((long) b[index + 1] << 8);
           l &= 0xffff;
           l |= ((long) b[index + 2] << 16);
           l &= 0xffffff;
           l |= ((long) b[index + 3] << 24);
           return Float.intBitsToFloat(l);
       }

    /**
     * 注释：字节数组到short的转换！
     * 无符号
     * @param b
     * @return
     */
    public static short byteToShort(byte[] b, int index) {
        short s = 0;
        short s0 = (short) (b[index] & 0xff);// 最低位
        short s1 = (short) (b[index+1] & 0xff);
        s1 <<= 8;
        s = (short) (s0 | s1);
        return s;
    }
    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
     private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**  
     * 字符串转换成十六进制字符串 
     * @param str str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B] 
     */    
    public static String str2HexStr(String str)  
    {    
  
        char[] chars = "0123456789ABCDEF".toCharArray();    
        StringBuilder sb = new StringBuilder("");  
        byte[] bs = str.getBytes();    
        int bit;

        for (byte b : bs) {
            bit = (b & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = b & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }    
        return sb.toString().trim();    
    }

    /**
     * bytes转换成十进制数字的字符串
     * @param byteArray byte数组
     * @return String
     */
    public static String byteArray2Str(byte[] byteArray)
    {
        if( byteArray!=null ){
            String tempStr;
            StringBuilder sb = new StringBuilder("");
            for (byte curByte : byteArray) {
                tempStr = Integer.toString(curByte);
                sb.append((tempStr.length() == 1) ? "0" + tempStr : tempStr);
                sb.append("");
            }
            return sb.toString().toUpperCase(Locale.CHINA).trim();
        }else{
            return "";
        }
    }

    /** 
     * bytes转换成十六进制字符串 
     * @param b b byte数组
     * @return String
     */  
    public static String byteArray2StrWithoutPrefix(byte[] b)
    {
        if( b!=null ){
            String stmp;
            StringBuilder sb = new StringBuilder("");
            for (byte aB : b) {
                stmp = Integer.toHexString(aB & 0xFF);
                sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
                sb.append("");
            }
            return sb.toString().toUpperCase(Locale.CHINA).trim();
        }else{
            return "";
        }
    }
    public static String byte2HexStrWithPrefix(byte[] b)
    {
        String stmp;
        StringBuilder sb = new StringBuilder("0x");
        for (byte aB : b) {
            stmp = Integer.toHexString(aB & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append("");
        }
        return sb.toString().toUpperCase(Locale.CHINA).trim();
    }

    /** 
     * bytes字符串转换为Byte值 
     * @param src src Byte字符串，每个Byte之间没有分隔符
     * @return byte[] 
     */  
    public static byte[] hexStr2Bytes(String src)  
    {  
        int m,n;
        int l=src.length()/2;
        byte[] ret = new byte[l];  
        for (int i = 0; i < l; i++)  
        {  
            m=i*2+1;  
            n=m+1;  
            ret[i] = Byte.decode("0x" + src.substring(i*2, m) + src.substring(m,n));  
        }  
        return ret;  
    }

    /**
     * bytes字符串转换为Byte值
     * @param src src Byte字符串，每个Byte之间没有分隔符
     * @return byte[]
     */
    public static byte[] str2Bytes(String src)
    {
        int byteArrayLength=src.length()/2;
        byte[] byteArray = new byte[byteArrayLength];
        for (int x = 0; x < byteArrayLength; x++)
        {
            String curStr = src.substring(x*2,x*2+2);
            byteArray[x] =  Byte.parseByte(curStr);
        }
        return byteArray;
    }


    /** 
     * String的字符串转换成unicode的String 
     * @param strText 全角字符串
     * @return String 每个unicode之间无分隔符 
     * @throws Exception 
     */  
    public static String strToUnicode(String strText)  
        throws Exception  
    {  
        char c;  
        StringBuilder str = new StringBuilder();  
        int intAsc;  
        String strHex;  
        for (int i = 0; i < strText.length(); i++)  
        {  
            c = strText.charAt(i);  
            intAsc = (int) c;  
            strHex = Integer.toHexString(intAsc);  
            if (intAsc > 128)  
                str.append("\\u").append(strHex);
            else // 低位在前面补00  
                str.append("\\u00").append(strHex);
        }  
        return str.toString();  
    }  
      
    /** 
     * unicode的String转换成String的字符串 
     * @param hex 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串 
     */  
    public static String unicodeToString(String hex)  
    {  
        int t = hex.length() / 6;  
        StringBuilder str = new StringBuilder();  
        for (int i = 0; i < t; i++)  
        {  
            String s = hex.substring(i * 6, (i + 1) * 6);  
            // 高位需要补上00再转  
            String s1 = s.substring(2, 4) + "00";  
            // 低位直接转  
            String s2 = s.substring(4);  
            // 将16进制的string转为int  
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);  
            // 将int转换为字符  
            char[] chars = Character.toChars(n);  
            str.append(new String(chars));  
        }  
        return str.toString();  
    } 
}
